
package net.swa.main.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;
import net.swa.dewei.beans.entity.FuwuZhan;
import net.swa.dewei.service.FuwuZhanService;
import net.swa.main.bean.IndexInfo;
import net.swa.system.beans.entity.Menu;
import net.swa.system.beans.entity.User;
import net.swa.system.service.ICommonService;
import net.swa.system.service.IMenuService;
import net.swa.system.util.SysConst;
import net.swa.system.web.action.AbstractBaseAction;
import net.swa.util.BuzConst;
import net.swa.util.EncryptTool;
import net.swa.util.JsonResult;

/**
 * 后台管理
 * 
 * @author Administrator
 * 
 */
public class MainAction extends AbstractBaseAction
{

    private static final long serialVersionUID = -8445520563685861470L;

    private ICommonService commonService;

    private IMenuService menuService;

    private FuwuZhanService fuwuZhanService;

    private List<Menu> roots;

    private User user;

    /*** 登陆名loginName ***/
    private String loginName;

    /*** 密码loginName ***/
    private String password;

    private String oldpwd;

    private static final Logger log = Logger.getLogger(MainAction.class);

    /**
     * 首页欢迎信息
     */
    private IndexInfo indexInfo;

    /**
     * 主页
     * 
     * @return
     * @throws Exception
     */
    public String main() throws Exception
    {
        log.debug("进入管理后台。。。");
        User user = (User) getSessionAttribute(SysConst.CURRENT_USER);
        if (null == user)
        {
            // 跳转到后台登陆页面
            return "adminlogin";
        }
        else
        {
            roots = menuService.getRootsByRoleId(getCurrentUser().getRole().getId());
        }
        return "main";
    }

    private String code;

    public String getCode()
    {
        return code;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    /**
     * 登陆页面
     * 
     * @return
     * @throws Exception
     */
    public String adminLogin() throws Exception
    {
        Object vc = getSession().getAttribute("validateCode");
        String validateCode = "";
        if (vc != null)
        {
            validateCode = vc.toString();
        }
        JsonResult<User> json = new JsonResult<User>();
        if (!validateCode.equalsIgnoreCase(code))
        {
            json.setSuccess(false);
            json.setMessage("1");
        }
        else
        {
            List<User> list = commonService.search("userid", user.getUserid(), User.class);
            if (list.size() == 0)
            {
                json.setSuccess(false);
                json.setMessage("用户不存在");
            }
            else
            {
                User dbUser = list.get(0);
                EncryptTool tool = new EncryptTool(user.getUserid());
                String password = tool.decrypt(dbUser.getPassword());
                if (password.equals(user.getPassword()))
                {
                    setSessionAttribute(SysConst.CURRENT_USER, dbUser);
                }
                else
                {
                    json.setSuccess(false);
                    json.setMessage("用户名或密码错误");
                }
            }
        }
        outJson(json);
        return null;
    }

    public String clientLogin() throws Exception
    {
        User loginUser = commonService.findByAttribute(User.class, "userid", loginName);
        EncryptTool tool = new EncryptTool(loginName);
        if (null != loginUser)
        {
            String psw = tool.encrypt(password);
            log.debug("平板端登陆，loginName is " + loginName + ",password is " + password);

            if (psw.equals(loginUser.getPassword()))// 将登陆页面上的16位进制的密码值转换成byte数组
            {
                if (null != loginUser.getFuwuzhanId() && SysConst.USER_TYPE_FUWUZHAN == loginUser.getUserType())
                {
                    FuwuZhan fuwuzhan = commonService.commonFind(FuwuZhan.class, loginUser.getFuwuzhanId());
                    if (null != fuwuzhan)
                    {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("success", true);
                        map.put("fuwuzhan", fuwuzhan);
                        map.put("message", "");
                        outJson(map);
                    }
                    else
                    {
                        outError("查询服务站出错");
                        log.debug("平板端登陆,error 查询服务站出错，loginName is " + loginName + ",password is " + password);
                    }
                }
                else
                {
                    outError("非服务站用户");
                    log.debug("平板端登陆,error 非服务站用户，loginName is " + loginName + ",password is " + password);
                }
            }
            else
            {
                outError("用户名或密码错误！");
                log.debug("平板端登陆,error 用户名或密码错误，loginName is " + loginName + ",password is " + password);
            }
        }
        else
        {
            outError("用户名或密码错误！");
        }
        return null;
    }

    public static void main(String[] args)
    {
        //        EncryptTool tool;
        //        try
        //        {
        //            tool = new EncryptTool("admin");
        //            String psw = tool.encrypt("administrator");
        //        }
        //        catch (Exception e)
        //        {
        //            e.printStackTrace();
        //        }
    }

    public String logout()
    {
        removeSessionAttribute(SysConst.CURRENT_USER);
        return "adminlogin";
    }

    /**
     * 进入修改密码页面
     * 
     * @return
     */
    public String profile()
    {
        return "updatePwd";
    }

    /**
     * 确定修改密码
     * 
     * @throws Exception
     */
    public String resetPwd() throws Exception
    {
        User u = getCurrentUser();
        if (null != u)
        {

            u = commonService.findByAttribute(User.class, "userid", u.getUserid());
            if (null != u)
            {
                EncryptTool tool = new EncryptTool(u.getUserid());
                String psw = tool.encrypt(oldpwd); // 将页面输入的密码进行加密，跟数据库中的加密密码进行
                // 比较（也可以吧数据库中的解密后比较（详细参考EncryptTool加密类））
                if (psw.equals(u.getPassword()))// 将登陆页面上的16位进制的密码值转换成byte数组
                {
                    u.setPassword(tool.encrypt(password));// 在放入session前，把用户密码设置成null
                    // 保证在session取不到用户密码(安全)
                    commonService.commonUpdate(u);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("success", true);
                    map.put("loginName", loginName);
                    map.put("message", "");
                    outJson(map);
                }
                else
                {
                    outError("密码输入错误");
                }
            }
            else
            {
                outError("ERROR");
            }
        }
        else
        {
            outError("请重新登录");
        }

        return null;
    }

    /**
     * 确定修改密码 client
     * 
     * @throws Exception
     */
    public String clientResetPwd() throws Exception
    {
        String userid = getRequestParameter("userid");
        if (!StringUtils.isBlank(userid))
        {
            log.debug("平板端更改密码，loginName is " + userid + ",password is " + oldpwd + ",new psw is " + password);
            User u = commonService.findByAttribute(User.class, "userid", userid);
            if (null != u)
            {
                if (SysConst.USER_TYPE_FUWUZHAN == u.getUserType())
                {
                    EncryptTool tool = new EncryptTool(u.getUserid());
                    String psw = tool.encrypt(oldpwd); // 将页面输入的密码进行加密，跟数据库中的加密密码进行
                    // 比较（也可以吧数据库中的解密后比较（详细参考EncryptTool加密类））
                    if (psw.equals(u.getPassword()))// 将登陆页面上的16位进制的密码值转换成byte数组
                    {
                        u.setPassword(tool.encrypt(password));// 在放入session前，把用户密码设置成null
                        // 保证在session取不到用户密码(安全)
                        commonService.commonUpdate(u);
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("success", true);
                        map.put("message", "");
                        outJson(map);
                    }
                    else
                    {
                        log.debug("平板端更改密码,密码输入错误，loginName is " + userid + ",password is " + oldpwd + ",new psw is "
                                + password);
                        outError("密码输入错误");
                    }
                }
                else
                {
                    log.debug("平板端更改密码,用户非服务站用户，loginName is " + userid + ",password is " + oldpwd + ",new psw is "
                            + password);
                    outError("用户非服务站用户");
                }
            }
            else
            {
                outError("ERROR");
            }
        }
        else
        {
            log.debug("平板端更改密码,请重新登录，loginName is " + userid + ",password is " + oldpwd + ",new psw is " + password);
            outError("请重新登录");
        }

        return null;
    }

    /**
     * 欢迎页面,进入“移动设备浏览”首页
     * 
     * @return
     * @throws Exception
     */

    public String index() throws Exception
    {

        return "index";
    }

    public List<Menu> getRoots()
    {
        return roots;
    }

    public void setRoots(List<Menu> roots)
    {
        this.roots = roots;
    }

    public ICommonService getCommonService()
    {
        return commonService;
    }

    @Resource
    @Required
    public void setCommonService(ICommonService commonService)
    {
        this.commonService = commonService;
    }

    public User getUser()
    {
        return user;
    }

    public void setUser(User user)
    {
        this.user = user;
    }

    public IndexInfo getIndexInfo()
    {
        return indexInfo;
    }

    public void setIndexInfo(IndexInfo indexInfo)
    {
        this.indexInfo = indexInfo;
    }

    public String getLoginName()
    {
        return loginName;
    }

    public void setLoginName(String loginName)
    {
        this.loginName = loginName;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public IMenuService getMenuService()
    {
        return menuService;
    }

    @Resource
    @Required
    public void setMenuService(IMenuService menuService)
    {
        this.menuService = menuService;
    }

    public String getOldpwd()
    {
        return oldpwd;
    }

    public void setOldpwd(String oldpwd)
    {
        this.oldpwd = oldpwd;
    }

    public FuwuZhanService getFuwuZhanService()
    {
        return fuwuZhanService;
    }

    @Resource
    @Required
    public void setFuwuZhanService(FuwuZhanService fuwuZhanService)
    {
        this.fuwuZhanService = fuwuZhanService;
    }

}
